package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.constructor.BaseConstructor;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.ClientRelations;
import com.example.demo.entity.ClientRelations2;
import com.example.demo.form.ClientRelation2Form;
import com.example.demo.service.ClientRelations2Service;
import com.example.demo.service.ClientRelationsService;

@RestController
@RequestMapping(value = "/ClientRelations")
public class ClientRelationsController extends BaseConstructor{
	@Autowired
	private ClientRelationsService service1;
	@Autowired
	private ClientRelations2Service service2;
	
	
	@RequestMapping(value = "/save")
	private Object save(ClientRelation2Form Form) throws ParseException {
		Integer insid1 = Form.getId();
		Date d= new Date();
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d1=dateFormat1.parse("1999-01-01");
		ClientRelations cli=new ClientRelations();
		ClientRelations Cli=new ClientRelations();
		ClientRelations2 cli2=new ClientRelations2();
		ClientRelations2 Cli2=new ClientRelations2();
		if(insid1==null) {
			Cli.setMonth(Form.getMonth());
			Cli.setYears(Form.getYears());
			cli=service1.save(Cli);
		}else {
			cli = service1.findById(insid1);
			Cli.setMonth(Form.getMonth());
			Cli.setYears(Form.getYears());
			service1.save(cli);
			List<ClientRelations2> list= service2.findByClientRelations(cli);
			for(ClientRelations2 Relations2:list) {
				if(d1.compareTo(Relations2.getBeginDate())==-1) {
					d1=Relations2.getBeginDate();
					Cli2=Relations2;
				}
			}
			Cli2.setEndDate(d);
			service2.save(Cli2);
		}
		BeanUtils.copyProperties(Form, cli2, "id");
		cli2.setClientRelations(cli);
		cli2.setBeginDate(d);
		service2.save(cli2);
		return new AjaxResult("数据保存成功");
	}
	
	@RequestMapping(value = "/findbydate")
	public Object findbyId() throws ParseException {
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d= dateFormat1.parse("1990-01-01");
		ClientRelations2 yan=new ClientRelations2();
		for(ClientRelations2 y : service2.findAll()) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				yan=y;
			}
		}
		return new AjaxResult(yan);
	}
}
